/*
 *  Copyright 2012.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.queryhandler.n.client.services;

import java.sql.SQLException;
import org.opu.queryhandler.n.client.services.beans.DataSource;
import org.opu.queryhandler.n.client.services.beans.DriverDefenition;
import org.opu.queryhandler.n.db.DbManager;
import org.opu.queryhandler.n.db.QueryResult;
import org.opu.queryhandler.n.util.Logger;

/**
 *
 */
public class DatabaseService {

    private DbManager dbManager;
    private Logger logger = Logger.getInstance();

    public boolean isDatabaseAvilable(){
        return dbManager != null;
    }
    
    public void initDbManager(DataSource ds) throws Exception {
        initDbManager(ds.getUrl(), ds.getUser(), ds.getPswd(), ds.getDriver());
    }

    public void initDbManager(String url, String usr, String pswd,
            DriverDefenition driver) throws Exception {

        logger.info(this, String.format("init database with: [url=%s] [user=%s]"
                + " [password=%s] [driver=%s]", url, usr, pswd, driver.getDriverClass()));

        if (driver.getFileLocation() != null){
            // TODO: we must load it
        }

        if (dbManager != null){
            dbManager.closeConnect();
            dbManager = null;
        }

        dbManager = new DbManager(url, usr, pswd, driver.getDriverClass());
    }

    public QueryResult executeQuery(String query) throws SQLException {
        if ("\\d".equals(query.trim())){
            return dbManager.getTables();
        } else {
            return dbManager.sendQuery(query);
        }
    }

    public void commit() throws SQLException{
        dbManager.commit();
    }

    public boolean isAutoCommit() throws SQLException{
        return dbManager.isAutoCommit();
    }

    public void rollback() throws SQLException {
        dbManager.rollback();
    }

    public boolean setAutoCommit(boolean b) throws SQLException {
        dbManager.setAutoCommit(b);
        return dbManager.isAutoCommit();
    }
}
